<template>
  <div class="search-container">
    <van-cell class="searchCell">
      <!-- 搜索栏》事件监听 -->
      <form
        action="/"
        class="searchForm"
      >
        <van-search
          v-model="searchText"
          show-action
          placeholder="请输入搜索关键词"
          @search="onSearch"
          @cancel="onCancel"
          background='#3296fa'
          @focus="isResultShow = false"
        />
      </form>
    </van-cell>

    <!-- /搜索栏 -->

    <!-- 结果记录 -->
    <SearchResult
      v-if="isResultShow"
      :search-text='searchText'
    />
    <!-- /结果记录 -->

    <!-- 联想建议 -->
    <SearchSuggestion
      :search-text="searchText"
      v-else-if="searchText"
      @searchText='onSearch'
    />
    <!-- /联想建议 -->

    <!-- 搜索历史记录 -->
    <SearchHistory
      :search-histories="searchHistories"
      v-else
      @search="onSearch"
    />
    <!-- /搜索历史记录 -->
  </div>
</template>

<script>
import SearchHistory from './components/search-history.vue'
import SearchSuggestion from './components/search-suggestion'
import SearchResult from './components/search-result'

import { setItem, getItem } from '@/utils/store.js'

import _ from 'lodash'

export default {
  name: 'search-container',
  data () {
    return {
      searchText: '',
      isResultShow: false,
      searchHistories: getItem('TOUTIAO_HISTORY') || []
    }
  },
  components: {
    SearchHistory,
    SearchSuggestion,
    SearchResult
  },
  watch: {
    searchHistories (value) {
      setItem('TOUTIAO_HISTORY', value)
    }
  },
  methods: {
    onSearch (val) {
      // this.$toast(val)
      this.searchText = val

      // // 存储搜索历史记录
      // 要求：不要有重复历史记录、最新的排在最前面
      // 去重的 三种方法
      // const index = this.searchHistories.indexOf(val)
      // if (index !== -1) {
      //   this.searchHistories.splice(index, 1)
      // }
      // this.searchHistories.unshift(val)

      // 方法二 set 特点：唯一
      // this.searchHistories.unshift(val)
      // this.searchHistories = [...new Set(this.searchHistories)]

      // 方法三 ladash
      this.searchHistories.unshift(val)
      this.searchHistories = _.uniq(this.searchHistories)

      this.isResultShow = true
    },
    onCancel () {
      this.$toast('取消')
      this.$router.back()
    }
  }
}
</script>

<style scoped lang='less'>
.search-container {
  padding-top: 106px;
  .van-search__action {
    color: #fff;
  }
  .searchForm {
    position: fixed;
    left: 0;
    top: 0;
    right: 0;
    z-index: 1;
  }
}
</style>
